import random  # 随机函数
from configparser import ConfigParser
import pypinyin
from docx.api import Document
from docx.shared import Pt, Cm, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_ALIGN_VERTICAL
from docx.oxml.shared import OxmlElement, qn
import math

# 使用哪个年级的文字列表，可以多个，用","隔开
grade_list = [1]
# 生成问题数量
TOTAL_QUESTIONS = 48
# 每行的列数，某认3列，其他列数，会影响格式，自行调整。
COLUMN = 3


def generator():
    config = ConfigParser()
    config.read('config.ini', encoding="utf-8-sig")
    characters = []
    words = []
    for grade in grade_list:
        characters.extend(config.get('character', 'grade-' + str(grade)).split(','))
        words.extend(config.get('words', 'grade-' + str(grade)).split(','))

    count = 0

    doc = Document()
    doc.styles['Normal'].font.name = u'宋体'
    doc.styles['Normal']._element.rPr.rFonts.set(qn('w:eastAsia'), u'宋体')
    paragraph = doc.add_paragraph()
    run = paragraph.add_run(
        "班级:___年___班    姓名:________     时间:___分___秒     分数:________")
    run.font.size = Pt(15)

    doc.sections[0].page_height = Cm(29.7)  # 设置A4纸的高度
    doc.sections[0].page_width = Cm(21)  # 设置A4纸的宽
    doc.sections[0].left_margin = Cm(1)  # 设置左边距
    doc.sections[0].right_margin = Cm(1)  # 设置右边距

    page_width = doc.sections[0].page_width.cm - doc.sections[0].left_margin.cm - doc.sections[0].right_margin.cm
    table = doc.add_table(rows=math.ceil(TOTAL_QUESTIONS / COLUMN), cols=COLUMN)
    table.style.width = Cm(page_width)
    table.style = 'Table Grid'
    question_char_list = []
    while True:
        words_len = len(words)
        if words_len == 0:
            break
        index = random.randint(0, words_len - 1)
        word = words.pop(index)
        word_list = list(word)
        pinyin_list = []
        char_not_found = True
        for index, char in enumerate(word_list):
            if char in characters:
                word_list[index] = '(   )'
                char_not_found = False
                question_char_list.append(char)
            pinyin_list.append(pypinyin.pinyin(char)[0][0])

        if char_not_found:
            continue

        print(word)
        row = count // COLUMN
        col = count % COLUMN
        cell = table.cell(row, col)
        cell.width = Cm(page_width / COLUMN)
        set_cell_margins(cell, top=0, start=0, bottom=0, end=0, left=0, right=0)
        cell.vertical_alignment = WD_ALIGN_VERTICAL.CENTER
        word_len = len(word)
        cell_table = cell.add_table(rows=2, cols=word_len)
        delete_paragraph(cell.paragraphs[0])
        for i in range(word_len):
            inline_word_cell = cell_table.cell(0, i)
            inline_word_cell.text = pinyin_list[i]
            inline_word_cell.width = Cm(page_width / COLUMN / word_len)
            set_cell_margins(inline_word_cell, top=0, start=0, bottom=0, end=0, left=0, right=0)
            inline_word_cell.paragraphs[0].runs[0].font.size = Pt(14)
            inline_word_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
            inline_word_cell.paragraphs[0].paragraph_format.line_spacing = 1

            inline_pinyin_cell = cell_table.cell(1, i)
            inline_pinyin_cell.text = word_list[i]
            inline_pinyin_cell.width = Cm(page_width / COLUMN / word_len)
            set_cell_margins(inline_pinyin_cell, top=0, start=0, bottom=0, end=0, left=0, right=0)
            inline_pinyin_cell.paragraphs[0].runs[0].font.size = Pt(15)
            inline_pinyin_cell.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.CENTER
            inline_pinyin_cell.paragraphs[0].paragraph_format.line_spacing = 1

        count += 1
        if count == TOTAL_QUESTIONS:
            break

    doc.save("拼音测试题.docx")


def delete_paragraph(paragraph):
    p = paragraph._element
    p.getparent().remove(p)
    paragraph._p = paragraph._element = None

def set_cell_margins(cell, **kwargs):
    '''设置某单元格间距

    长度单位为Twips，1Twips = 1/20pt，1Twips = 1/567cm

    >>> set_cell_margins(table.cell(1, 0), top=0, start=0, bottom=0, end=0, left=0, right=0)

    :param cell: 某单元格
    :param top: 上边距
    :param start: 左边距
    :param bottom: 下边距
    :param end: 右边距
    :param left: 左边距（WPS）
    :param right: 右边距（WPS）
    '''
    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()
    tcMar = OxmlElement('w:tcMar')
    for m in ['top', 'start', 'bottom', 'end', 'left', 'right']:
        if m in kwargs:
            node = OxmlElement('w:{}'.format(m))
            node.set(qn('w:w'), str(kwargs.get(m)))
            node.set(qn('w:type'), 'dxa')
            tcMar.append(node)
    tcPr.append(tcMar)



if __name__ == '__main__':
    generator()
